const { User } = require('../models/index')
const { Counter } = require('../models/counters')
const crudUtil = require('./crudUtil')
const jwt = require('jsonwebtoken')
const util = require('../utlis/common')
const md5 = require('md5')
//添加 
const userAdd = async (ctx) => {
    let { usename, pwd } = ctx.request.body
    await crudUtil.add(User, { usename, pwd }, ctx)
}
//修改
const userUpdae = async (ctx) => {
    let params = ctx.request.body
    await crudUtil.update(User, { _id: params._id },
        { usename: params.usename, pwd: params.pwd },
        ctx
    )
}

// 添加用户 //编辑
const userMssgerAdd = async (ctx) => {
    const { userid, usename, userEmail, mobile, job, status, rolelist, deptId,remark, action } = ctx.request.body
    if (action == 'add') {
        if (!usename || !userEmail || !deptId) {
            ctx.status = 404
            ctx.body = util.fail('参数错误', util.USER_LOGIN_ERROR)
            return
        }
        const res = await User.findOne({ $or: [{ usename }, { userEmail }] }, '_id,usename,userEmail')
        if (res) {
            ctx.body = util.fail(`用户已存在，信息${res.nickName}-${res.userEmail}`)
        } else {
            const doc = await Counter.findOneAndUpdate({ id: 'userid' }, { $inc: { sequence_value: 1 } }, { new: true })
            try {
                 User.create({
                    userid: doc.sequence_value,
                    pwd: md5('123456'),
                    usename,
                    userEmail,
                    role: '1', //默认普通用户
                    rolelist,
                    job,
                    deptId,
                    mobile,
                    status,
                    startTime:Date.now(),
                    remark
                })
                ctx.body = util.success('', '用户创建成功')
            } catch (error) {
                ctx.status = 404
                ctx.body = util.fail(error.stack, '用户创建失败')
            }

        }

    } else {
        if (!deptId) {
            ctx.body = util.fail('部门不能为空', util.CODE.PARAM_ERROR)
            return
        }
        try {
            const res = await User.findOneAndUpdate({ userid }, { userEmail, mobile, job, status, rolelist, deptId })
            ctx.body = util.success({}, '更新成功')
        } catch (error) {
            ctx.body = util.fail(error.stack, '更新失败')
        }
    }

}

//删除用户
const userDel = async (ctx) => {
    let { ids } = ctx.request.body
    console.log('ids',ids)
    try {
        const res = await User.updateMany({ userid: { $in: ids } }, { status: 0 })
        ctx.body = util.success(res, `共删除${res.nModified}条`)
    } catch (error) {
        ctx.body = util.fail('删除失败')
    } 
}
// 用户列表
const userFindAll = async (ctx) => {
    const { userid, username, status } = ctx.request.query
    const { page, skipIndex } = util.pager(ctx.request.query)
    let params = {}
    if (userid) params.userid = userid
    if (username) params.username = username
    if (status && status != 0) params.status = status
    try {
        // 根据条件查询所有列表
        const query = User.find(params, { pwd: 0,_id:0 })
        const list = await query.skip(skipIndex).limit(page.pageSize)
        const total = await User.countDocuments(params)
        ctx.body = util.success({
            page: {
                ...page,
                total,
            },
            data: list
        })
    } catch (error) {
        ctx.body = util.fail(`查询异常:${error.stack}`)
    }
}

//用户登录
const userFindOne = async (ctx) => {
    let { usename, pwd } = ctx.request.query
    let passwrod = md5(pwd)
    await User.findOne({ usename, passwrod })
        .then(rel => {
            if (rel) {
                let data = rel._doc
                const token = jwt.sign(
                    { data: data },
                    'hyhadmin',
                    { expiresIn: 60}
                )
                ctx.body = {
                    code: 200,
                    msg: 'ok',
                    data: { ...data, token }
                }
            } else {
                ctx.body = {
                    code: 404,
                    msg: '参数错误',
                    data: rel
                }
            }

        }).catch(error => {
            ctx.body = {
                code: 400,
                msg: '异常'
            }
            console.log(error)
        })
}
module.exports = {
    userAdd,
    userUpdae,
    userDel,
    userFindAll,
    userFindOne,
    userMssgerAdd,
}